<!-- 人工智能 -->
<template>
  <div class="dashboard-editor-container">
    <div style="display:flex;justify-content:space-between;">
      <partitionTree dialogName="分类" :nodeData="CustomerList" FileName="xxx" :addTemplate="true"
        :defaultProps="defaultProps" :defaultExpandAll="true" @handleNodeClick="handleNodeClick" ref="partitionTree"
        @toggleVisibility="toggleVisibility" @addDepartment="getData">
      </partitionTree>
      <div :style="{ width: containerWidth }" class="box"
        style="background:#fff;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
        <el-row style="background: #fff; padding: 16px 16px 0;">
          <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset" />
          <div class="tabclick">
            <div class="tabitem" @click="handleClick()">
              <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
            </div>
          </div>
          <el-row>
            <el-tabs type="border-card" v-if="tab" style="margin-top:16px;" @tab-click="tabClick">
              <el-tab-pane label="显示日统计趋势" lazy>
                <el-col :xs="24" :sm="24" :lg="24">
                  <barchart :title="'显示日统计趋势'" :chartData="barchartData" @barclick="echartsClick" />
                </el-col>
              </el-tab-pane>
              <el-tab-pane label="终端统计分析" lazy>
                <el-row :gutter="20">
                  <el-col :xs="24" :sm="24" :lg="24">
                    <piechart :title="'终端统计分析'" :chartData="pie1Data" @pieclick="echartsClick" />
                  </el-col>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </el-row>
          <!-- <barchart /> -->
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }"
            style="padding-right: 8px;margin:16px 0;">
            <!-- <span class="title">人工智能列表</span> -->
            <el-button type="primary" @click="handleAdd">添加企业智库</el-button>
            <el-table stripe :data="tableData" style="width: 100%; margin-top: 15px;">
              <el-table-column label="序号" width="60" type="index"
                :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
              <el-table-column prop="Title" label="标题" show-overflow-tooltip />
              <el-table-column prop="Class" label="分类" width="120" show-overflow-tooltip />
              <el-table-column prop="UserID" label="用户" width="120" />
              <el-table-column prop="CreateTime" label="发布时间" width="180">
                <template slot-scope="{row}">
                  <span>{{ parseTime(row.CreateTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="UpdateTime" label="更新时间" width="180">
                <template slot-scope="{row}">
                  <span>{{ parseTime(row.UpdateTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="Property" label="知识属性" width="80">
                <template slot-scope="{row}">
                  <span :style="{ color: row.Property === 2 ? '#67C23A' : '#F56C6C' }">{{ row.Property === 2 ? '共享' :
                    '私有' }}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="ContentLink" label="内容" show-overflow-tooltip /> -->
              <el-table-column label="操作" width="220" fixed="right">
                <template slot-scope="scope">
                  <el-button size="small" type="primary" @click="handleEdit(scope.row)">修改</el-button>
                  <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                  <el-button size="small" type="success" @click="handlePreview(scope.row)">预览</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page=pageNum
              :page-size=pageSize background layout="total, prev, pager, sizes, next, jumper" :total="total">
            </el-pagination>
          </el-col>
        </el-row>
      </div>
    </div>
    <KnowledgeBaseDialog :classList="classList" :Action="Action" :dialogForm="dialogForm" :dialogVisible="dialogVisible"
      @closeDialog="closeDialog" @submitDialog="submitDialog" />
  </div>
</template>

<script>
import Cookies from "js-cookie";
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import {
  getNowDay,
  parseTime,
  getTreeData,
  ParamDictURLtype,
  Maintype
} from "@/utils/index.js";
import { connrequest, uploadfile } from "@/api/firstPage.js";
import connsearch from "@/components/connSearch";
import KnowledgeBaseDialog from "./components/KnowledgeBaseDialog.vue";
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
import partitionTree from "@/components/partitionTree";
export default {
  directives: { elDragDialog },
  components: {
    connsearch,
    barchart,
    piechart,
    KnowledgeBaseDialog,
    partitionTree
  },
  data() {
    let that = this;
    return {
      Action: 1,
      tabTitle: "显示日统计趋势",
      tableData: [],
      containerWidth: 'calc(100% - 240px)',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      UUID: "",
      dialogForm: {
        ContentLink: ''
      },
      tab: false,
      type: '',
      dialogVisible: false,
      question: "",
      answer: "",
      searchobj: {},
      barchartData: { xAxis: [], series: [] },
      pie1Data: [],
      previewList: [],
      classList: [],
      searchform: {},
      mapping: [],//定义一个变量接收res.Data
      CustomerList: [
        {
          Class: "所有企业智库",
          children: []
        }
      ],
      defaultProps: {
        children: "children",
        label: "Class"
      },
      formOptions: [
        {
          col: 10,
          label: "更新时间",
          prop: "timeRange",
          element: "el-date-picker",
          initValue: [],
          type: "",
          events: {
            input(val) {
              that.searchform.timeRange = val;
            }
          }
        },
        {
          col: 8,
          label: "标题",
          prop: "Descp",
          element: "el-input",
          placeholder: "请输入标题,支持模糊查询。",
          events: {
            input(val) {
              that.searchform.Descp = val;
            }
          }
        }
      ]
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get("DefaultPageLength") * 1;
    let endTime = new Date(new Date().setHours(0, 0, 0, 0));
    let startTime =
      endTime - Cookies.get("DefaultLogDays") * 1 * 3600 * 24 * 1000;
    let arr = [parseTime(startTime), ""];
    this.formOptions.map((item) => {
      if (item.label === "更新时间") {
        item.initValue = arr;
      }
    });
    this.$set(this.searchform, "timeRange", arr);
    // this.GetDictKnowledgeClass();
    this.getData();
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {

  },
  methods: {
    parseTime,
    // 将树结构数据转换成级联选择器要展示的数据
    transformData(data) {
      return data.map(item => ({
        value: item.ID,
        label: item.Class,

        children: item.children && item.children.length ? this.transformData(item.children) : null
      }));
    },
    // 处理数据table表的数据，通过table.ID=== classList.ID添加 Class 字段
    processData(data) {
      return data.map((item) => {
        // 在 classList 中查找匹配的 ID
        const matchedClass = this.mapping.find((cls) => cls.ID === item.ClassID); // 确保类型匹配
        return {
          ...item,
          Class: matchedClass ? matchedClass.Class : "未知分类" // 如果匹配则赋值，否则用默认值
        };
      });
    },
    copyAnswer(data) {
      let elInput = document.createElement("textarea");
      elInput.value = data;
      document.body.appendChild(elInput);
      // 选择对象
      elInput.select();
      // 执行浏览器复制命令
      this.$message.success("复制成功");
      document.execCommand("Copy");
      elInput.remove();
    },
    async getData(searchobj = {}) {
      await this.GetDictKnowledgeClass();
      await this.GetDictKnowledge(searchobj);
      switch (this.tabTitle) {
        case "显示日统计趋势":
          this.GetDictKnowledgeSumGroupByDate(searchobj);
          break;
        default:
          this.GetDictKnowledgeSumGroupByUser(searchobj);
          break;
      }
    },
    echartsClick(val, title, id) {
      this.pageNum = 1;
      if (title === "显示日统计趋势") {
        this.searchobj = {
          StartTime: `${val} 00:00:00`,
          EndTime: `${val} 23:59:59`
        };
        this.GetDictKnowledge(this.searchobj);
        this.GetDictKnowledgeClass(this.searchobj);
      } else if (title === "终端统计分析") {
        this.searchobj = { Name: val };
        this.GetDictKnowledge(this.searchobj);
        this.GetDictKnowledgeClass(this.searchobj);
      }
    },
    tabClick(row) {
      this.tabTitle = row.label;
      switch (this.tabTitle) {
        case "显示日统计趋势":
          this.GetDictKnowledgeSumGroupByDate();
          break;
        default:
          this.GetDictKnowledgeSumGroupByUser();
          break;
      }
    },
    async handleNodeClick({ data }) {
      this.pageNum = 1;
      this.searchobj = {
        MainClassID: data.ID === 0 ? "" : data.ID
      };
      this.GetDictKnowledge({
        MainClassID: data.ID === 0 ? "" : data.ID
      });
    },
    // 获取企业智库分类
    async GetDictKnowledgeClass(searchobj = {}) {
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || "",
          EndTime: this.searchform.timeRange?.[1] || "",
          Descp: this.searchform.Descp || "",
          ClassName: this.searchform.ClassName || "",
          ...searchobj
        }
      };
      const res = await connrequest("GetDictKnowledgeClass", data);
      res.Data.map((item) => {
        item.Name = item.Class;
      });
      this.CustomerList[0].children = this.buildTree(res.Data);
      this.mapping = res.Data;
      this.classList = this.transformData(this.CustomerList[0].children);
      // this.GetDictKnowledge();
    },
    async submitDialog(submitdata, Action) {
      // 将字符串转为Blob
      const blob = new Blob([submitdata.ContentLink], { type: "text/plain" }); // 指定MIME类型为text/plain
      // 将Blob转为File对象，指定文件名
      const file = new File([blob], "test.txt", { type: "text/plain" });
      let formData = new FormData();
      formData.append("CmdCode", "UploadFileToTmp");
      if (Action === 2) {
        formData.append("UUID", this.UUID);
      }
      formData.append("file", file);
      const fileUUID = await uploadfile(formData);
      this.dialogVisible = false;
      try {
        const data = {
          Data: {
            Action: Action,
            Detail: {
              UserID: sessionStorage.getItem("username"),
              ...submitdata,
              ContentLink: fileUUID.Data.UUID
            }
          }
        };
        const res = await connrequest("EditDictKnowledge", data);
        if (res && res.Status.StatusCode === 0) {
          this.getData();
          this.$message.success(Action === 1 ? "添加成功" : "修改成功");
        } else {
          this.$message.error("添加失败");
        }
      } catch (error) {
        this.$message.error(error.Status.Msg2Client);
      }
    },
    handleAdd() {
      this.Action = 1;
      this.dialogForm = {
        Title: "",
        ClassID: this.classList.value?.[0]?.Class ?? "",
        Property: 2

      };

      this.openDialog();
    },
    async handleEdit(row) {

      this.UUID = row.ContentLink;
      this.Action = 2;
      const fileUrl = `/knowledge/${row.ContentLink}`;
      const response = await fetch(fileUrl);
      if (!response.ok) {
        this.$message.error("企业智库获取失败");
        return false;
      }
      const text = await response.text();
      this.$nextTick(() => {
        this.dialogForm = { ...row, ContentLink: text };
      })
      this.openDialog();
      // this.$set(this.dialogForm, 'ContentLink', text)
    },
    async handleDelete(row) {
      try {
        await this.$msgbox.confirm("确定删除该企业智库吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        const data = {
          Data: {
            Action: 3,
            Detail: {
              ...row
            }
          }
        };
        const res = await connrequest("EditDictKnowledge", data);
        if (res && res.Status.StatusCode === 0) {
          this.getData(this.searchobj);
          this.$message.success("删除成功");
        } else {
          this.$message.error("删除失败");
        }
      } catch (error) {
        if (error !== "cancel") {
          this.$message.error("删除企业智库请求错误");
        }
      }
    },
    async handlePreview(row) {
      this.Action = 4;
      const fileUrl = `/knowledge/${row.ContentLink}`;
      const response = await fetch(fileUrl);
      if (!response.ok) {
        this.$message.error("企业智库获取失败");
        return false;
      }
      const text = await response.text();
      this.dialogForm = { ...row, ContentLink: text };
      this.openDialog();
    },
    //     async handlePreview (row) {
    //   try {
    //     const fileUrl = `/knowledge/${row.ContentLink}`;
    //     // 发起请求以获取内容
    //     const response = await fetch(fileUrl);
    //     if (!response.ok) {
    //       ElMessage.error("企业智库获取失败");
    //       return;
    //     }
    //     // 获取文本内容
    //     const text = await response.text();
    //     console.log("55555555555",text);

    //     // 确保 HTML 内容包含字符编码声明
    //     // 如果服务器未正确设置 Content-Type，可以手动添加 <meta> 标签
    //     const htmlWithMeta = `
    //       <!DOCTYPE html>
    //       <html lang="zh-CN">
    //       <head>
    //         <meta charset="UTF-8">
    //         <title>标题：${row.Title}</title>
    //       </head>
    //       <body>
    //         ${text}
    //       </body>
    //       </html>
    //     `;
    //     // 创建一个 Blob 对象，并指定 MIME 类型为 text/html; charset=utf-8
    //     const blob = new Blob([htmlWithMeta], { type: 'text/html; charset=utf-8' });
    //     // 创建一个 URL 对象
    //     const blobUrl = URL.createObjectURL(blob);
    //     // 打开一个新窗口
    //     const newWindow = window.open(blobUrl, '_blank');
    //     // 立即将新窗口的 opener 设置为 null，防止其通过 window.opener 访问原始窗口
    //     if (newWindow) {
    //       newWindow.opener = null;
    //     }
    //     // 可选：在适当的时机释放 Blob URL 以节省资源
    //     // 例如，可以在新窗口关闭时调用 URL.revokeObjectURL(blobUrl)
    //     // 需要额外逻辑来跟踪和管理 Blob URL 的生命周期
    //   } catch (error) {
    //     console.error("预览时发生错误:", error);
    //     ElMessage.error("预览时发生错误");
    //   }
    // },

    openDialog() {
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
      this.dialogForm.ContentLink = ' '
    },
    // 获取事件日期统计
    async GetDictKnowledgeSumGroupByDate() {
      let xAxis = [];
      let series = [];
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || "",
          EndTime: this.searchform.timeRange?.[1] || "",
          Descp: this.searchform.Descp || ""
        }
      };
      const res = await connrequest("GetDictKnowledgeSumGroupByDate", data);
      res.Data = res.Data || [];
      res.Data.map((item) => {
        xAxis.push(item.Name);
        series.push(item.Count);
      });
      this.barchartData = { xAxis, series };
    },
    // 获取审计用户统计
    async GetDictKnowledgeSumGroupByUser() {
      let arr = [];
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || "",
          EndTime: this.searchform.timeRange?.[1] || "",
          TransDate: "",
          Descp: this.searchform.Descp || "",
          ClassName: this.searchform.ClassName || ""
        }
      };
      const res = await connrequest("GetDictKnowledgeSumGroupByUser", data);
      res.Data = res.Data || [];
      res.Data.map((item) => {
        arr.push({ name: item.Name, value: item.Count });
      });
      this.pie1Data = arr;
    },
    // 获取人工智能列表
    async GetDictKnowledge(searchobj = {}) {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || "",
          EndTime: this.searchform.timeRange?.[1] || "",
          Descp: this.searchform.Descp || "",
          ...searchobj
        }
      };
      const res = await connrequest("GetDictKnowledge", data);
      res.Data = res.Data || [];
      this.tableData = this.processData(res.Data);
      this.total = res.Paging.TotalCount;
    },
    handleSizeChange(val) {
      this.pageNum = 1;
      this.pageSize = val;
      this.GetDictKnowledge(this.searchobj);
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.GetDictKnowledge(this.searchobj);
    },
    search(val) {
      this.pageNum = 1;
      this.searchform = { ...val };
      if (this.searchform.timeRange) {
        this.searchobj = {
          StartTime: this.searchform?.timeRange[0] || "",
          EndTime: this.searchform?.timeRange[1] || ""
        };
      }
      this.getData();
    },

    reset() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0));
      let startTime =
        endTime - Cookies.get("DefaultLogDays") * 1 * 3600 * 24 * 1000;
      let arr = [parseTime(startTime), ""];
      this.pageNum = 1;
      this.formOptions = this.formOptions.map((item) => {
        if (item.label === "更新时间") {
          item.initValue = arr;
        } else {
          item.initValue = "";
        }
        return item;
      });
      this.searchform = {};
      this.$set(this.searchform, "timeRange", arr);
      this.$refs.connsearch.addInitValue();
      this.getData();
    },
    handleClick() {
      this.tab = !this.tab;
    },
    toggleVisibility(isHidden) {
      if (isHidden) this.containerWidth = "100%";
      else this.containerWidth = "calc(100% - 240px)";
    },
    // 将获取到的分类信息转化成树状结构
    buildTree(data) {
      const map = {};
      const roots = [];

      // 初始化每个节点的 Children 数组
      data.forEach((item) => {
        map[item.ID] = { ...item, children: [] };
      });

      // 构建树关系
      data.forEach((item) => {
        if (item.ParentID === 0) {
          roots.push(map[item.ID]);
        } else {
          if (map[item.ParentID]) {
            map[item.ParentID].children.push(map[item.ID]);
          }
        }
      });

      return roots;
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";
@import "./components/css/conncss.scss";

.AIanswer {
  width: calc(100% - 70px);
  height: 400px;
  overflow: auto;
}

.demo-image {
  display: flex;

  .block {
    width: 300px;
  }
}

::v-deep .el-table {
  display: flex;
  flex-direction: column;
}

/* 设置垂直滚动条（如果需要水平滚动条，请添加::-webkit-scrollbar-horizontal选择器） */
::-webkit-scrollbar {
  width: 3px;
  /* 滚动条宽度 */
}

/* 滚动条轨道部分（即背景） */
::-webkit-scrollbar-track {
  background-color: #fff;
  /* 背景颜色 */
}

/* 滚动条上下两端的按钮 */
::-webkit-scrollbar-button {
  display: none;
  /* 隐藏按钮 */
}

/* 滚动条滑块部分（即滑块本身） */
::-webkit-scrollbar-thumb {
  background-color: #ccc;
  /* 滑块颜色 */
}

.copyButton {
  position: absolute;
  bottom: 10px;
  right: 20px;
  z-index: 100000000;
  color: #409eff;
}

.right {
  width: calc(100% - 240px);
  margin-left: 20px;
  padding: 20px;
}

.night {
  .xxx {
    background: #2a2d3c;

    ::v-deep .el-tabs__item {
      color: #fff;
    }

    ::v-deep .el-tabs__item.is-active,
    ::v-deep .el-tabs__item:hover {
      color: #1890ff;
    }
  }

  .right {
    background: #303445;
  }

  .box-content {
    margin: 20px;
  }
}
</style>